package com.dj.uphome.web.service.system.impl;

import java.util.List;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dj.common.web.exception.ServiceHandleException;
import com.dj.common.web.service.impl.BaseCrudServiceImpl;
import com.dj.common.web.vo.PageAndSortVo;
import com.dj.uphome.web.mapper.system.SysUserMapper;
import com.dj.uphome.web.service.system.SysUserService;
import com.dj.uphome.web.vo.system.SysUserVo;

@Service
public class SysUserServiceImpl extends BaseCrudServiceImpl<SysUserVo> implements SysUserService {

	@Autowired
	private SysUserMapper sysUserMapper;
	
	@Override
	@Transactional
	public SysUserVo create(SysUserVo vo) throws Exception {
		if(vo.getUserId()>0) {
			if(StringUtils.isNotEmpty(vo.getPassword())) {
				vo.setPassword(new SimpleHash("SHA-1", vo.getUserName(), vo.getPassword()).toString());
			}
			sysUserMapper.update(vo);
		}else {
			//保存时踢出一些敏感登录名称
			if(null!=vo.getUserName()&&SysUserVo.sensitiveUserName.contains(vo.getUserName())) {
				throw new ServiceHandleException("登录账号不能包含敏感账号，请换一个账号名称再试试！");
			}
			vo.setPassword(new SimpleHash("SHA-1", vo.getUserName(), vo.getPassword()).toString());
			sysUserMapper.save(vo);
		}
		return vo;
	}
	@Override
	public SysUserVo getUserByNameAndPwd(String userName,String password) throws Exception {
		return sysUserMapper.getUserInfo(userName,password);
	}

	@Override
	public SysUserVo getUserByUserName(String userName) throws Exception {
		return sysUserMapper.getUserByUserName(userName);
	}

	@Override
	public Page<SysUserVo> findPage(Pageable pageRequest, SysUserVo vo) throws Exception {
		PageAndSortVo<SysUserVo> pageVo = convertToPageAndSortVo(pageRequest, vo,true);
		List<SysUserVo> contentList = sysUserMapper.findAll(pageVo);
		return new PageImpl<>(contentList, pageRequest, pageVo.getTotalResult());
	}

	@Override
	@Transactional
	public void delete(int id) throws Exception {
		sysUserMapper.deleteById(id);
	}

	@Override
	public SysUserVo findOne(int id) throws Exception {
		return sysUserMapper.findById(id);
	}

}
